/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_products/gitcan.htm
 *
 * gitcan is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.gitcan.action.equipment;

import java.util.List;

import org.zhiqim.gitcan.dbo.GitIdc;
import org.zhiqim.gitcan.dbo.GitMachine;
import org.zhiqim.gitcan.dbo.GitMachineEx;
import org.zhiqim.gitsolo.dao.GitMemberDao;
import org.zhiqim.gitsolo.dao.GitProjectDao;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.extend.StdSwitchAction;
import org.zhiqim.httpd.validate.ones.IsIntegerValue;
import org.zhiqim.httpd.validate.ones.IsLen;
import org.zhiqim.httpd.validate.ones.IsNotEmpty;
import org.zhiqim.httpd.validate.onex.IsIP;
import org.zhiqim.httpd.validate.onex.IsInteger;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;


/**
 * 服务器管理，支持服务器的创建、删除和修改权限
 *
 * @version v1.0.0 @author zhichenggang 2014-3-21 新建与整理
 */
public class MachineAction extends StdSwitchAction
{
    @Override
    protected void validateId(HttpRequest request)
    {
        request.addValidate(new IsNotEmpty("machineId", "请选择一个选项"));
    }

    @Override
    protected void validateForm(HttpRequest request)
    {
        request.addValidate(new IsInteger("idcId", "请选择机房"));
        request.addValidate(new IsLen("machineName", "服务器名称不能为空，[1, 32]范围", 1, 32));
        request.addValidate(new IsIP("machineIp", "服务器IP地址不正确"));
        request.addValidate(new IsIntegerValue("machineType", "服务器类型仅支持[windows/linux]", 0, 1));
        request.addValidate(new IsNotEmpty("machineUser", "服务器用户名不能为空"));
        request.addValidate(new IsIntegerValue("machinePort", "服务器管理端口不能为空，[1, 65534]范围", 1, 65534));
        request.addValidate(new IsIntegerValue("machineSeq", "服务器排序必须是[0, 999999]范围的非负整数", 0, 999999));
        request.addValidate(new IsIP("machineInternetIp", "服务器公网IP地址不正确，没有请置空", true));
    }

    @Override
    protected void list(HttpRequest request) throws Exception
    {
        int pageNo = request.getParameterInt("page", 1);
        int pageSize = request.getContextAttributeInt("zmr_page_size", 20);
        
        Selector selector = new Selector();
        selector.addMust("projectId", GitProjectDao.getProjectId(request));
        selector.addMaybeLike("machineName", request.getParameter("machineName"));
        selector.addOrderbyAsc("machineSeq");
        
        PageResult<GitMachineEx> result = ORM.view().page(GitMachineEx.class, pageNo, pageSize, selector);
        result.addConditionMap(request.getParameterMap());
        
        request.setAttribute("result", result);
    }
    
    @Override
    protected void add(HttpRequest request) throws Exception
    {
        Selector selector = new Selector();
        selector.addMust("projectId", GitProjectDao.getProjectId(request));
        selector.addOrderbyAsc("idcSeq");
        
        List<GitIdc> list = ORM.table().list(GitIdc.class, selector);
        request.setAttribute("list", list);
    }

    @Override
    protected void modify(HttpRequest request) throws Exception
    {
        long machineId = request.getParameterLong("machineId");
        GitMachine item = ORM.table().item(GitMachine.class, machineId);
        
        if (!GitProjectDao.chkProjectId(request, item.getProjectId()))
        {//判断是否切换了默认项目
            return;
        }
        
        request.setAttribute("item", item);
    }

    @Override
    protected void insert(HttpRequest request) throws Exception
    {
        String machinePassword = request.getParameter("machinePassword");
        if (Validates.isEmptyBlank(machinePassword))
        {
            request.returnHistory("服务器管理员密码不能为空");
            return;
        }
        
        long projectId = GitProjectDao.getProjectId(request);
        String machineIp = request.getParameter("machineIp");
        if (ORM.table().count(GitMachine.class, new Selector("projectId", projectId).addMust("machineIp", machineIp)) > 0)
        {
            request.returnHistory("该服务器IP已存在，请不要重复增加");
            return;
        }
        
        long idcId = request.getParameterLong("idcId");
        String machineName = request.getParameter("machineName");
        int machineType = request.getParameterInt("machineType");
        String machineUser = request.getParameter("machineUser");
        int machinePort = request.getParameterInt("machinePort");
        int machineSeq = request.getParameterInt("machineSeq");
        String machineInternetIp = request.getParameter("machineInternetIp");
        String machineExpirationDate = request.getParameter("machineExpirationDate");
        
        GitMachine item = new GitMachine();
        item.setProjectId(projectId);
        item.setIdcId(idcId);
        item.setMachineId(Ids.longId());
        item.setMachineName(machineName);
        item.setMachineIp(machineIp);
        item.setMachineType(machineType);
        item.setMachineUser(machineUser);
        item.setMachinePassword(machinePassword);
        item.setMachinePort(machinePort);
        item.setMachineSeq(machineSeq);
        item.setMachineInternetIp(machineInternetIp);
        item.setMachineExpirationDate(machineExpirationDate);
        
        ORM.table().insert(item);
        
        GitMemberDao.report(request, projectId, request.getSessionName(), "创建了服务器", machineName);
    }

    @Override
    protected void update(HttpRequest request) throws Exception
    {
        long machineId = request.getParameterLong("machineId");
        GitMachine item = ORM.table().item(GitMachine.class, machineId);
        if(item == null)
        {
            request.returnHistory("服务器不存在，请重新选择");
            return;
        }
        
        if (!GitProjectDao.chkProjectId(request, item.getProjectId()))
        {//判断是否切换了默认项目
            return;
        }
        
        Updater updater = new Updater();
        updater.addMust("machineId", machineId);
        updater.addField("machineName", request.getParameter("machineName"));
        updater.addField("machineStatus", request.getParameterInt("machineStatus"));
        updater.addField("machineType", request.getParameterInt("machineType"));
        updater.addField("machineUser", request.getParameter("machineUser"));
        updater.addField("machineSeq", request.getParameterInt("machineSeq"));
        updater.addField("machinePort", request.getParameterInt("machinePort"));
        updater.addField("machineInternetIp", request.getParameter("machineInternetIp"));
        updater.addField("machineExpirationDate", request.getParameter("machineExpirationDate"));
        
        String machinePassword = request.getParameter("machinePassword");
        if (Validates.isNotEmpty(machinePassword))
        {//密码不为空才修改
            updater.addField("machinePassword", machinePassword);
        }
        
        ORM.table().update(GitMachine.class, updater);
        
        GitMemberDao.report(request, item.getProjectId(), request.getSessionName(), "修改了服务器", request.getParameter("machineName"));
    }

    @Override
    protected void delete(HttpRequest request) throws Exception
    {
        long machineId = request.getParameterLong("machineId");
        GitMachine item = ORM.table().item(GitMachine.class, machineId);
        if(item == null)
        {
            request.returnHistory("服务器不存在，请重新选择");
            return;
        }
        
        if (!GitProjectDao.chkProjectId(request, item.getProjectId()))
        {//判断是否切换了默认项目
            return;
        }
        
        ORM.table().delete(GitMachine.class, machineId);
        
        GitMemberDao.report(request, item.getProjectId(), request.getSessionName(), "删除了服务器", item.getMachineName());
    }
}
